package day4;

import java.lang.reflect.Field;
import java.util.Date;

//反射测试 设置和获取单个属性
public class TestField {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        //1. 获取类对象
        Class c = Persion.class;
        //2.获取单个属性
        Field idField = c.getDeclaredField("id");
        Field nameField = c.getDeclaredField("name");
        Field dateFiled = c.getDeclaredField("birthday");
        idField.setAccessible(true);

        System.out.println("----------------");
        //获取Persion的所有属性，包括私有属性
        Field[] field = c.getDeclaredFields();
        for (Field field1 : field) {
            System.out.println(field1);
        }
        //3.设置和获取属性值
        Persion p = new Persion();
        nameField.set(p, "钟元");
        dateFiled.set(p, new Date());
        idField.set(p,1000);
        //获取属性值
        System.out.println(p.name + " " + p.birthday);
        //通过反射获取属性值
        //get(对象) 用于获取属性值
        Object value1 = nameField.get(p);
        Object value2 = dateFiled.get(p);
        Object value3 = idField.get(p);

        System.out.println(value1 + " " + value2 + " " + value3);
    }
}
